
package com.amkai.aes.webservice.binary.objecthandler;

import java.io.Serializable;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amkai.aes.aescommon.factory.RADBeanFactory;
import com.amkai.aes.aescommon.service.binary.job.AmkaiRxRegistrationJob;
import com.amkai.aes.aescommon.service.result.AmkaiRxRegistrationResult;
import com.amkai.aes.generatedbeans.common.Address;
import com.amkai.aes.generatedbeans.organization.AmkaiRx;
import com.amkai.aes.generatedbeans.organization.Department;
import com.amkai.aes.generatedbeans.organization.Enterprise;
import com.amkai.aes.generatedbeans.organization.PrescriberRegistration;
import com.amkai.aes.generatedbeans.personnel.details.License;
import com.amkai.aes.generatedbeans.physstaff.LicenseKind;
import com.amkai.aes.generatedbeans.physstaff.PhysStaffSpecialtyAssociation;
import com.amkai.aes.generatedbeans.physstaff.Physician;
import com.amkai.aes.generatedbeans.physstaff.Specialty;
import com.amkai.aes.generatedbeans.physstaff.SpecialtyQualifier;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;
import com.amkai.erx.communicator.AmkaiRxCommunicator;

public class AmkaiRxRegistrationHandler implements JobObjectHandler<AmkaiRxRegistrationJob, java.io.Serializable, AmkaiRxRegistrationResult> {
	private static final Log log = LogFactory.getLog(AmkaiRxRegistrationHandler.class);
	@Override
	public AmkaiRxRegistrationResult process(AmkaiRxRegistrationJob job,Serializable object) throws Exception {
		AmkaiRxRegistrationResult ret = new AmkaiRxRegistrationResult();
		switch(job.kind) {
		case GET_DEAS:
			getDEAs(job, ret);
			break;
		case REG_DEA:
			registerDEA(job,ret);
			break;
		}
			
		return ret;
	}
	
	private void registerDEA(AmkaiRxRegistrationJob job,AmkaiRxRegistrationResult ret) throws Exception {
		SessionManager sm = SiteManager.Start();
		try {
			sm.openSession();
			Enterprise ent = (Enterprise) sm.execute("from Enterprise").uniqueResult();
			String url = ent.getAmkaiRxURL();
			Department dep = sm.get(Department.class, job.getModuleDepartment().getId());
			AmkaiRx arx = dep.getAmkaiRx();
			if(arx == null) {
				ret.errorMessage= "This department is not registered.";
				return;
			}
//			arx.get
//			AmkaiRxCommunicator arc = new AmkaiRxCommunicator();
			
			Physician phys = sm.get(Physician.class, job.physId);
			Address a = (Address) sm.execute("select a from Address a where a.person.id = "+phys.getPerson().getId()+" and a.main = 1").uniqueResult();
			if(a == null) {
				ret.errorMessage = "There is no main address specified for the physician.";
				return;
			}
			String zip = a.getLocation().getZipCode().getZip().getName();
			License lic = sm.get(License.class, job.licenseId);
			Long siteId = arx.getSiteID();
			String loginName = arx.getLoginUserName();
			String loginPassword = arx.getLoginPassword();

			String city = a.getLocation().getZipCode().getCity().getName();
			String state = a.getLocation().getZipCode().getZip().getState().getName();
			String line1 = a.getLocation().getLine1();

			String line2 = a.getLocation().getLine2();
			String dea = lic.getAccreditaionNumber();
			String firstName = phys.getPerson().getFirstName();
			String lastName = phys.getPerson().getLastName();
			
			String middleName = phys.getPerson().getMiddleInitial();
			
			String phoneNumber = a.getLocation().getPhone() == null ? null : a.getLocation().getPhone().getNumber();
			String faxNumber = a.getLocation().getFax() == null ? null : a.getLocation().getFax().getNumber();
			
			if(phoneNumber == null) {
				ret.errorMessage = "There is no Phone number for the physician.";
				return;
			}
			if(faxNumber == null) {
				ret.errorMessage = "There is no Fax number for the physician.";
				return;
			}
			
/*
15 bit = for future use (currently 0) 
14 bit = for future use (currently 0) 
13 bit = for future use (currently 0) 
12 bit = for future use (currently 0) 
11 bit = for future use (currently 0) 
10 bit = for future use (currently 0) 
9 bit = for future use (currently 0) 
8 bit = for future use (currently 0) 
7 bit = for future use (currently 0) 
6 bit = 1 if Eligibility is supported,0 if Eligibility is not supported 
5 bit = 1 if Medication History supported, 0 if Medication History not supported 
4 bit = 1 if CanRx/CanRxRes supported, 0 if CanRx/CanRxRes not supported
3 bit = 1 if RxFill supported, 0 if RxFill not supported 
2 bit = 1 if RxChg/ChgRes supported, 0 if RxChg/ChgRes not supported 
1 bit = 1 if RefReq/RefRes supported, 0 if RefReq/RefRes not supported 
0 bit = 1 if NewRx supported, 0 if NewRx not supported
 */
			int serviceLevel = Integer.parseInt("1101111", 2); //canrx unsupported
			serviceLevel = 1;
			Specialty spec = null;
			SpecialtyQualifier specialtyQualifier = null;//SpecialtyQualifier.AM.value();
			for(PhysStaffSpecialtyAssociation sssa : phys.getPhysStaffSpecialtyAssociations()) {
				//if(sssa.is)
				spec = sssa.getSpecialty();
				specialtyQualifier = sssa.getSpecialityQualifier();
			}
			if(spec == null) {
				ret.errorMessage = "There is no Specialty for the physician.";
				return;
			}
			if(specialtyQualifier == null) {
				ret.errorMessage = "There is no Specialty Qualifier for the physician.";
				return;
			}
			String specialtyCode = spec.getAmaSpecialtyCode();
			if(specialtyCode == null) {
				ret.errorMessage = "There is no Specialty Code for the physician.";
				return;
			}
			String ssid = AmkaiRxCommunicator.registerPhysician(url, siteId, loginName, loginPassword, city, line1, line2, state, dea, firstName, lastName, middleName, phoneNumber, faxNumber, serviceLevel, specialtyCode, specialtyQualifier.name(), zip);
			if(ssid.startsWith("!")) {
				//error handling
				ret.errorMessage = ssid.substring(1);
			} else {
				PrescriberRegistration pr = RADBeanFactory.getInstance().createBean(PrescriberRegistration.class);
				pr.setPhysician(phys);
				pr.setLicense(lic);
				pr.setPrescriberId(ssid);
				sm.saveRADInTransaction(pr);
				ret.prescriberRegistration = pr;
			}
		} finally {
			sm.closeSession();
		}
	}

	private void getDEAs(AmkaiRxRegistrationJob job, AmkaiRxRegistrationResult ret) throws Exception {
		SessionManager sm = SiteManager.Start();
		
		try {
			sm.openSession();
			ArrayList<License>lics = new ArrayList<License>();
			Physician phys = sm.get(Physician.class, job.physId);
			System.out.println(":::GET DEAS "+phys.getPerson().getDisplayName());
			for (License lic : phys.getPersonnelInfo().getAccreditation().getLicenses()) {
				LicenseKind lk = lic.getKind().getLicenseKind();
				if(lk == LicenseKind.DEA) {
					lic.getAccreditaionNumber();
					lic.getEffectiveDate();
					lic.getExpirationDate();
					for(PrescriberRegistration pr : lic.getPrescriberRegistrations()) {
						pr.getPrescriberId();
					}
					lics.add(lic);
				}
			}
			ret.deas = lics;
		} finally {
			sm.closeSession();
		}
	}
}
